package com.bridgeintelligent.tag.webserver.dim.mgmt.service.indexdim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bridgeintelligent.tag.mapper.CatalogMapper;
import com.bridgeintelligent.tag.mapper.IndexDimMapper;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimCatalog;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.indexdim.DimInfoModel;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.indexdim.IndexDimModel;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.indexdim.IndexNameInfo;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.indexdim.TimeSymbolModel;
import com.bridgeintelligent.tag.webserver.dim.query.api.service.IQueryService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@AllArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class IndexDimServiceImpl implements IIndexDimService {

    private IndexDimMapper indexInfoMapper;

    private IQueryService queryService;

    private CatalogMapper catalogMapper;

    @Override
    public List<IndexNameInfo> indexNameList(String indexStatus) {
        return indexInfoMapper.findIndexNameListByStatus(indexStatus);
    }

    @Override
    public List<IndexDimModel> IndexDimList() {
        return indexInfoMapper.findIndexDimList();
    }

    @Override
    public void addIndexDimInfo(IndexDimModel indexDimModel) {
        //计算增长ID
        Integer maxIndexId = indexInfoMapper.findMaxIndexId();
        if (maxIndexId == null){
            maxIndexId = 1;
        }else{
            maxIndexId = maxIndexId+1;
        }
        indexDimModel.setId(maxIndexId);
        indexDimModel.setIndexStatus("1");//未启用状态
        indexInfoMapper.addIndexDimInfo(indexDimModel);
    }

    @Override
    public void updateIndexDimInfo(IndexDimModel indexDimModel) {
        indexDimModel.setIndexStatus("1");
        indexInfoMapper.updateIndexDimInfo(indexDimModel);
    }

    @Override
    public void delIndexDimInfo(Integer id) {
        indexInfoMapper.delIndexDimInfo(id);
        indexInfoMapper.delIndexNameInfo(String.valueOf(id));
        indexInfoMapper.delIndexTimeInfo(String.valueOf(id));
    }

    @Override
    public IndexDimModel findIndexDimById(Integer id) {
        return indexInfoMapper.findIndexDimById(id);
    }

    @Override
    public void updateUpIndexStatus(Integer id) {
        //修改IndexDim状态
        indexInfoMapper.updateIndexDimStatus("0",id);
        //根据ID查询IndexDim信息
        IndexDimModel indexDim = indexInfoMapper.findIndexDimById(id);
        if (indexDim != null){
            IndexNameInfo dbIndexName = indexInfoMapper.findIndexNameById(String.valueOf(id));
            if (dbIndexName == null ){//说明第一次启动
                //插入索引表
                IndexNameInfo indexName = new IndexNameInfo()
                        .setId(String.valueOf(indexDim.getId()))
                        .setIndexType("_doc")
                        .setDataDate(indexDim.getIndexCode())
                        .setName(indexDim.getIndexName())
                        .setIndexStatus("0")
                        .setThemeKey("cust_id"+id);
                indexInfoMapper.addIndexNameInfo(indexName);
                //插入时间表
                List<TimeSymbolModel> times = JSONArray.parseArray(indexDim.getTimeSymbol(), TimeSymbolModel.class);
                times.forEach(e->{
                    e.setIndexId(String.valueOf(id));
                    indexInfoMapper.addIndexTimeInfo(e);
                });
            }else{
                indexInfoMapper.updateIndexNameStatus("0",String.valueOf(id));
            }
        }
    }

    @Override
    public void updateDownIndexStatus(Integer id) {
        indexInfoMapper.updateIndexDimStatus("1",id);
        indexInfoMapper.updateIndexNameStatus("1",String.valueOf(id));
    }

    @Override
    public boolean checkCodeOrName(int type, String id, String indexCode, String indexName) {
        //校验indexCode
        if (type == 0){
            IndexDimModel indexByCode = indexInfoMapper.findIndexByCode(indexCode);
            if (indexByCode == null ){
                return false;
            }else {
                if (id.equals(indexByCode.getIndexCode())){
                    return false;
                }
            }
            return true;
        }else{
            IndexDimModel indexByName = indexInfoMapper.findIndexByName(indexName);
            if (indexByName == null ){
                return false;
            }else {
                if (id.equals(indexByName.getIndexName())){
                    return false;
                }
            }
            return true;
        }
    }

    @Override
    public List<String> findCatalogIdByDims(String indexId) {
        List<String> list = new ArrayList<>();
        //根据ID查询IndexDim信息
        IndexDimModel indexDim = indexInfoMapper.findIndexDimById(Integer.valueOf(indexId));
        if (indexDim != null && !StringUtils.isEmpty(indexDim.getIndexDim())){
            List<DimInfoModel> dimInfoModels = JSONArray.parseArray(indexDim.getIndexDim(), DimInfoModel.class);
            List<String> dimIds = dimInfoModels.stream().map(e -> e.getDimId()).collect(Collectors.toList());
            List<String> catalogs = indexInfoMapper.findCatalogIdByDimId(dimIds);
            List<String> distcatalogs = catalogs.stream().distinct().collect(Collectors.toList());
            for (String catalogId:distcatalogs) {
                checkAllCatalog(catalogId,list);
            }

        }
        log.info("获取目录："+ JSON.toJSONString(list));
        return list;
    }

    @Override
    public void updateStatusById(String id, String status) {
        indexInfoMapper.updateIndexDimStatus(status,Integer.valueOf(id));
    }

    private List<String> checkAllCatalog(String catalogId,List<String> list) {
        list.add(catalogId);
        DimCatalog catalogInfo = catalogMapper.findById(catalogId);
        if (catalogInfo.getLevel() != 1){
            checkAllCatalog(catalogInfo.getParentId(),list);
        }
        return list;
    }




}
